#include <gtest/gtest.h>
#include <cmath>
extern "C" {
#include "math_functions.h"  // 包含头文件，而非 .c 文件
}

// 测试 power 函数
TEST(MathFunctionsTest, PowerFunction) {
    // 测试正指数
    EXPECT_EQ(power(2, 3), 8);
    // 测试负指数
    EXPECT_EQ(power(2, -3), 1.0 / 8);
    // 测试指数为 0
    EXPECT_EQ(power(2, 0), 1);
    // 测试底数为 0
    EXPECT_EQ(power(0, 3), 0);
    // 测试底数为 0 且指数为负数
    EXPECT_EQ(power(0, -3), std::numeric_limits<double>::infinity());
}

// 测试 logarithm 函数
TEST(MathFunctionsTest, LogarithmTest) {
    EXPECT_NEAR(logarithm(100, 10), 2, 1e-9);
    EXPECT_NEAR(logarithm(8, 2), 3, 1e-9);
}

// 测试 factorial 函数
TEST(MathFunctionsTest, FactorialTest) {
    EXPECT_EQ(factorial(0), 1);
    EXPECT_EQ(factorial(5), 120);
}

// 测试 permutation 函数
TEST(MathFunctionsTest, PermutationTest) {
    EXPECT_EQ(permutation(5, 3), 60);
    EXPECT_EQ(permutation(3, 5), 0);
}

// 测试 combination 函数
TEST(MathFunctionsTest, CombinationTest) {
    EXPECT_EQ(combination(5, 3), 10);
    EXPECT_EQ(combination(3, 5), 0);
}

// 测试 solveQuadratic 函数
TEST(MathFunctionsTest, SolveQuadraticFunction) {
    // 测试判别式大于 0 的情况
    QuadraticSolution sol1 = solveQuadratic(1, -3, 2);
    EXPECT_EQ(sol1.real_roots, 2);
    EXPECT_EQ(sol1.root1, 2);
    EXPECT_EQ(sol1.root2, 1);

    // 测试判别式等于 0 的情况
    QuadraticSolution sol2 = solveQuadratic(1, -2, 1);
    EXPECT_EQ(sol2.real_roots, 1);
    EXPECT_EQ(sol2.root1, 1);
    EXPECT_EQ(sol2.root2, 1);

    // 测试判别式小于 0 的情况
    QuadraticSolution sol3 = solveQuadratic(1, 0, 1);
    EXPECT_EQ(sol3.real_roots, 0);
    EXPECT_EQ(sol3.root1, 0);
    EXPECT_EQ(sol3.root2, 0);
}

// 测试几何计算函数
TEST(GeometryFunctionsTest, CircleAreaTest) {
    double radius = 2.0;
    double expected = PI * radius * radius;
    EXPECT_NEAR(circleArea(radius), expected, 1e-9);
}

TEST(GeometryFunctionsTest, SphereVolumeTest) {
    double radius = 2.0;
    double expected = (4.0 / 3.0) * PI * pow(radius, 3);
    EXPECT_NEAR(sphereVolume(radius), expected, 1e-9);
}

TEST(GeometryFunctionsTest, CylinderVolumeTest) {
    double radius = 2.0;
    double height = 3.0;
    double expected = PI * radius * radius * height;
    EXPECT_NEAR(cylinderVolume(radius, height), expected, 1e-9);
}

TEST(GeometryFunctionsTest, ConeVolumeTest) {
    double radius = 2.0;
    double height = 3.0;
    double expected = (1.0 / 3.0) * PI * radius * radius * height;
    EXPECT_NEAR(coneVolume(radius, height), expected, 1e-9);
}

// 测试三角函数扩展函数
TEST(TrigonometryFunctionsTest, DegreeToRadianTest) {
    double degrees = 180.0;
    double expected = degrees * (PI / 180.0);
    EXPECT_NEAR(degreeToRadian(degrees), expected, 1e-9);
}

TEST(TrigonometryFunctionsTest, RadianToDegreeTest) {
    double radians = PI;
    double expected = radians * (180.0 / PI);
    EXPECT_NEAR(radianToDegree(radians), expected, 1e-9);
}

TEST(TrigonometryFunctionsTest, SineTest) {
    double degrees = 90.0;
    double expected = sin(degreeToRadian(degrees));
    EXPECT_NEAR(sine(degrees), expected, 1e-9);
}

TEST(TrigonometryFunctionsTest, CosineTest) {
    double degrees = 0.0;
    double expected = cos(degreeToRadian(degrees));
    EXPECT_NEAR(cosine(degrees), expected, 1e-9);
}

TEST(TrigonometryFunctionsTest, TangentTest) {
    double degrees = 45.0;
    double expected = tan(degreeToRadian(degrees));
    EXPECT_NEAR(tangent(degrees), expected, 1e-9);
}

TEST(TrigonometryFunctionsTest, HyperbolicSineTest) {
    double x = 1.0;
    double expected = sinh(x);
    EXPECT_NEAR(hyperbolicSine(x), expected, 1e-9);
}

TEST(TrigonometryFunctionsTest, HyperbolicCosineTest) {
    double x = 1.0;
    double expected = cosh(x);
    EXPECT_NEAR(hyperbolicCosine(x), expected, 1e-9);
}

// 定义一个简单的测试函数
double testFunction1(double x) {
    return x * x;
}

// 测试导数计算
TEST(CalculusTest, DerivativeTest) {
    double x = 2.0;
    double h = 0.0001;
    double expected = 2 * x; // 函数 x^2 的导数是 2x
    double result = derivative(testFunction1, x, h);
    EXPECT_NEAR(result, expected, 0.001);
}

// 测试积分计算
TEST(CalculusTest, IntegralTest) {
    double a = 0.0;
    double b = 2.0;
    int n = 1000;
    double expected = (2.0 * 2.0 * 2.0) / 3.0; // 函数 x^2 从 0 到 2 的积分是 (2^3)/3
    double result = integral(testFunction1, a, b, n);
    EXPECT_NEAR(result, expected, 0.01);
}



// 简单的测试函数 f(x) = x^2 - 4
double testFunction2(double x) {
    return x * x - 4;
}

// 测试函数 f(x) 的导数 f'(x) = 2x
double testFunctionDerivative(double x) {
    return 2 * x;
}

// 测试 tmean 函数
TEST(StatisticalFunctionsTest, TMeanTest) {
    double arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    double expected = (1 + 2 + 3 + 4 + 5) / 5.0;
    EXPECT_EQ(tmean(arr, size), expected);
}

// 测试 median 函数
TEST(StatisticalFunctionsTest, MedianTest) {
    double arr1[] = {1, 2, 3, 4, 5};
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
    EXPECT_EQ(median(arr1, size1), 3);

    double arr2[] = {1, 2, 3, 4};
    int size2 = sizeof(arr2) / sizeof(arr2[0]);
    EXPECT_EQ(median(arr2, size2), (2 + 3) / 2.0);
}

// 测试 tvariance 函数
TEST(StatisticalFunctionsTest, TVarianceTest) {
    double arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    double mean = tmean(arr, size);
    double sum = 0;
    for (int i = 0; i < size; i++) {
        sum += (arr[i] - mean) * (arr[i] - mean);
    }
    double expected = sum / size;
    EXPECT_EQ(tvariance(arr, size), expected);
}

// 测试 standardDeviation 函数
TEST(StatisticalFunctionsTest, StandardDeviationTest) {
    double arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    double variance = tvariance(arr, size);
    double expected = sqrt(variance);
    EXPECT_EQ(standardDeviation(arr, size), expected);
}

// 测试 range 函数
TEST(RangeTest, BasicTest) {
    double arr1[] = {1, 2, 3, 4, 5};
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
    double result1 = range(arr1, size1);
    EXPECT_EQ(result1, 4); // 最大值 5 减去最小值 1 等于 4

    double arr2[] = {10, 20, 30, 40, 50};
    int size2 = sizeof(arr2) / sizeof(arr2[0]);
    double result2 = range(arr2, size2);
    EXPECT_EQ(result2, 40); // 最大值 50 减去最小值 10 等于 40

    double arr3[] = {5, 5, 5, 5, 5};
    int size3 = sizeof(arr3) / sizeof(arr3[0]);
    double result3 = range(arr3, size3);
    EXPECT_EQ(result3, 0); // 所有元素相同，极差为 0

    double arr4[] = {5, 4, 3, 2, 1};
    int size4 = sizeof(arr4) / sizeof(arr4[0]);
    double result4 = range(arr4, size4);
    EXPECT_EQ(result4, 4); // 所有元素相同，极差为 0
}


// 测试协方差函数
// TEST(StatisticsTest, CovarianceTest) {
//     double arr1[] = {1, 2, 3, 4, 5};
//     double arr2[] = {2, 4, 6, 8, 10};
//     int size = sizeof(arr1) / sizeof(arr1[0]);
//     double result = covariance(arr1, arr2, size);
//     // 这里可以根据手动计算或理论值来调整期望值
//     EXPECT_NEAR(result, 2.0, 1e-6); 
// }

// 测试 newtonRaphson 函数
TEST(NumericalMethodsTest, NewtonRaphsonTest) {
    double guess = 3;
    double tol = 1e-6;
    double result = newtonRaphson(testFunction2, testFunctionDerivative, guess, tol);
    EXPECT_NEAR(result, 2, tol);
}

// 测试 linearInterpolation 函数
TEST(NumericalMethodsTest, LinearInterpolationTest) {
    double x[] = {1, 2, 3};
    double y[] = {2, 4, 6};
    int n = sizeof(x) / sizeof(x[0]);
    double xi = 1.5;
    double expected = 2 + ((4 - 2) / (2 - 1)) * (1.5 - 1);
    EXPECT_EQ(linearInterpolation(x, y, n, xi), expected);

    double x1[] = {1, 2, 3};
    double y1[] = {2, 4, 6};
    int n1 = sizeof(x1) / sizeof(x1[0]);
    double xi1 = 2.5;
    double expected1 = 2 + ((4 - 2) / (2 - 1)) * (2.5 - 1);
    EXPECT_EQ(linearInterpolation(x1, y1, n1, xi1), expected1);

    double x2[] = {1, 2, 3};
    double y2[] = {2, 4, 6};
    int n2 = sizeof(x2) / sizeof(x2[0]);
    double xi2 = 4.5;
    double expected2 = 0;
    EXPECT_EQ(linearInterpolation(x2, y2, n2, xi2), expected2);
}

// 测试 is_prime 函数
TEST(NumberTheoryTest, IsPrimeTest) {
    EXPECT_EQ(is_prime(1), 0);
    EXPECT_EQ(is_prime(2), 1);
    EXPECT_EQ(is_prime(3), 1);
    EXPECT_EQ(is_prime(4), 0);
    EXPECT_EQ(is_prime(5), 1);
    EXPECT_EQ(is_prime(6), 0);
    EXPECT_EQ(is_prime(35), 0);
    EXPECT_EQ(is_prime(49), 0);
    EXPECT_EQ(is_prime(121), 0);
}



// 测试 gcd 函数
TEST(NumberTheoryTest, GCDTest) {
    EXPECT_EQ(gcd(12, 18), 6);
    EXPECT_EQ(gcd(24, 36), 12);
    EXPECT_EQ(gcd(5, 7), 1);
}

// 测试 lcm 函数
TEST(NumberTheoryTest, LCMTest) {
    EXPECT_EQ(lcm(4, 6), 12);
    EXPECT_EQ(lcm(3, 5), 15);
}

// 测试 fibonacci 函数
TEST(NumberTheoryTest, FibonacciTest) {
    EXPECT_EQ(fibonacci(0), 0);
    EXPECT_EQ(fibonacci(1), 1);
    EXPECT_EQ(fibonacci(2), 1);
    EXPECT_EQ(fibonacci(3), 2);
    EXPECT_EQ(fibonacci(4), 3);
}

// 测试 clamp 函数
TEST(EnhancedMathTest, ClampTest) {
    EXPECT_EQ(clamp(5, 1, 10), 5);
    EXPECT_EQ(clamp(0, 1, 10), 1);
    EXPECT_EQ(clamp(15, 1, 10), 10);
}

// 测试 sigmoid 函数
TEST(EnhancedMathTest, SigmoidTest) {
    double expected = 1.0 / (1.0 + exp(-1.0));
    EXPECT_NEAR(sigmoid(1.0), expected, 1e-9);
}

// 测试 radians_to_degrees 函数
TEST(EnhancedMathTest, RadiansToDegreesTest) {
    double expected = M_PI * (180.0 / M_PI);
    EXPECT_NEAR(radians_to_degrees(M_PI), expected, 1e-9);
}

// 测试 degrees_to_radians 函数
TEST(EnhancedMathTest, DegreesToRadiansTest) {
    double expected = 180.0 * (M_PI / 180.0);
    EXPECT_NEAR(degrees_to_radians(180.0), expected, 1e-9);
}

// 测试 log_base_10 函数
TEST(EnhancedMathTest, LogBase10Test) {
    double expected = log10(100);
    EXPECT_NEAR(log_base_10(100), expected, 1e-9);
}

// 测试 log_base_2 函数
TEST(EnhancedMathTest, LogBase2Test) {
    double expected = log2(8);
    EXPECT_NEAR(log_base_2(8), expected, 1e-9);
}

// 测试 reciprocal 函数
TEST(EnhancedMathTest, ReciprocalTest) {
    EXPECT_EQ(reciprocal(2.0), 0.5);
}

// 测试 cube_root 函数
TEST(EnhancedMathTest, CubeRootTest) {
    double expected = cbrt(8);
    EXPECT_NEAR(cube_root(8), expected, 1e-9);
}

// 测试 hypotenuse 函数
TEST(EnhancedMathTest, HypotenuseTest) {
    double expected = hypot(3, 4);
    EXPECT_NEAR(hypotenuse(3, 4), expected, 1e-9);
}

// 测试取整函数
TEST(RoundingFunctionsTest, RoundToTest) {
    EXPECT_EQ(round_to(3.14159, 2), 3.14);
}

TEST(RoundingFunctionsTest, CFloorTest) {
    EXPECT_EQ(cfloor(3.14159, 2), 3.14);
}

TEST(RoundingFunctionsTest, CCeilTest) {
    EXPECT_EQ(cceil(3.14159, 2), 3.15);
}

// 测试统计扩展函数
TEST(StatisticsFunctionsTest, SumTest) {
    double arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    EXPECT_EQ(sum(arr, size), 15);
}

TEST(StatisticsFunctionsTest, ProductTest) {
    double arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    EXPECT_EQ(product(arr, size), 120);
}

// 测试数值校验函数
TEST(ValidationFunctionsTest, IsPowerOfTwoTest) {
    EXPECT_EQ(is_power_of_two(8), 1);
    EXPECT_EQ(is_power_of_two(9), 0);
}

TEST(ValidationFunctionsTest, IsEvenTest) {
    EXPECT_EQ(is_even(4), 1);
    EXPECT_EQ(is_even(5), 0);
}

TEST(ValidationFunctionsTest, IsOddTest) {
    EXPECT_EQ(is_odd(5), 1);
    EXPECT_EQ(is_odd(4), 0);
}

// 测试范围操作函数
TEST(RangeFunctionsTest, MapRangeTest) {
    EXPECT_EQ(map_range(5, 0, 10, 0, 100), 50);
}

TEST(RangeFunctionsTest, InRangeTest) {
    EXPECT_EQ(in_range(5, 0, 10), 1);
    EXPECT_EQ(in_range(15, 0, 10), 0);
}

// 测试单位转换函数
TEST(UnitConversionFunctionsTest, CelsiusToFahrenheitTest) {
    EXPECT_EQ(celsius_to_fahrenheit(0), 32);
}

TEST(UnitConversionFunctionsTest, FahrenheitToCelsiusTest) {
    EXPECT_EQ(fahrenheit_to_celsius(32), 0);
}

TEST(UnitConversionFunctionsTest, KilometersToMilesTest) {
    EXPECT_NEAR(kilometers_to_miles(1), 0.621371, 1e-6);
}

TEST(UnitConversionFunctionsTest, MilesToKilometersTest) {
    EXPECT_NEAR(miles_to_kilometers(1), 1 / 0.621371, 1e-6);
}

// 测试随机数函数
TEST(RandomFunctionsTest, RandomIntTest) {
    int min = 1;
    int max = 10;
    int result = random_int(min, max);
    EXPECT_TRUE(result >= min && result <= max);
}

TEST(RandomFunctionsTest, RandomDoubleTest) {
    double min = 1.0;
    double max = 10.0;
    double result = random_double(min, max);
    EXPECT_TRUE(result >= min && result <= max);
}

// 测试符号处理函数
TEST(SignFunctionsTest, CopySignTest) {
    double magnitude = 5.0;
    double sign = -1.0;
    double result = copy_sign(magnitude, sign);
    EXPECT_EQ(result, -5.0);
}

TEST(SignFunctionsTest, SignTest) {
    EXPECT_EQ(sign(5.0), 1);
    EXPECT_EQ(sign(-5.0), -1);
    EXPECT_EQ(sign(0.0), 0);
}

// 测试浮点数比较函数
TEST(FloatComparisonTest, FloatEqualTest) {
    double a = 0.1 + 0.2;
    double b = 0.3;
    double epsilon = 1e-9;
    EXPECT_TRUE(float_equal(a, b, epsilon));
}

// 测试矩阵创建
// TEST(MatrixTest, CreateMatrix) {
//     int rows = 3;
//     int cols = 4;
//     Matrix mat = matrix_create(rows, cols);
//     printf("Testing matrix: rows = %d, cols = %d\n", mat.rows, mat.cols);
//     EXPECT_EQ(mat.rows, rows);
//     EXPECT_EQ(mat.cols, cols);
//     for (int i = 0; i < rows; i++) {
//         for (int j = 0; j < cols; j++) {
//             EXPECT_EQ(mat.data[i][j], 0.0);
//         }
//     }
//     matrix_free(&mat);
// }



// 测试矩阵克隆
TEST(MatrixTest, CloneMatrix) {
    Matrix mat = matrix_create(2, 2);
    matrix_set(&mat, 0, 0, 1.0);
    matrix_set(&mat, 0, 1, 2.0);
    matrix_set(&mat, 1, 0, 3.0);
    matrix_set(&mat, 1, 1, 4.0);

    Matrix clone = matrix_clone(&mat);
    EXPECT_EQ(clone.rows, mat.rows);
    EXPECT_EQ(clone.cols, mat.cols);
    for (int i = 0; i < mat.rows; i++) {
        for (int j = 0; j < mat.cols; j++) {
            EXPECT_EQ(matrix_get(&clone, i, j), matrix_get(&mat, i, j));
        }
    }
    matrix_free(&mat);
    matrix_free(&clone);
}


// 测试矩阵加法
TEST(MatrixTest, MatrixAddition) {
    Matrix a = matrix_create(2, 2);
    matrix_set(&a, 0, 0, 1.0);
    matrix_set(&a, 0, 1, 2.0);
    matrix_set(&a, 1, 0, 3.0);
    matrix_set(&a, 1, 1, 4.0);

    Matrix b = matrix_create(2, 2);
    matrix_set(&b, 0, 0, 5.0);
    matrix_set(&b, 0, 1, 6.0);
    matrix_set(&b, 1, 0, 7.0);
    matrix_set(&b, 1, 1, 8.0);

    Matrix result = matrix_add(&a, &b);
    EXPECT_EQ(result.rows, a.rows);
    EXPECT_EQ(result.cols, a.cols);
    EXPECT_EQ(matrix_get(&result, 0, 0), 6.0);
    EXPECT_EQ(matrix_get(&result, 0, 1), 8.0);
    EXPECT_EQ(matrix_get(&result, 1, 0), 10.0);
    EXPECT_EQ(matrix_get(&result, 1, 1), 12.0);

    matrix_free(&a);
    matrix_free(&b);
    matrix_free(&result);
}

// 测试矩阵减法
TEST(MatrixTest, MatrixSubtraction) {
    Matrix a = matrix_create(2, 2);
    matrix_set(&a, 0, 0, 5.0);
    matrix_set(&a, 0, 1, 6.0);
    matrix_set(&a, 1, 0, 7.0);
    matrix_set(&a, 1, 1, 8.0);

    Matrix b = matrix_create(2, 2);
    matrix_set(&b, 0, 0, 1.0);
    matrix_set(&b, 0, 1, 2.0);
    matrix_set(&b, 1, 0, 3.0);
    matrix_set(&b, 1, 1, 4.0);

    Matrix result = matrix_subtract(&a, &b);
    EXPECT_EQ(result.rows, a.rows);
    EXPECT_EQ(result.cols, a.cols);
    EXPECT_EQ(matrix_get(&result, 0, 0), 4.0);
    EXPECT_EQ(matrix_get(&result, 0, 1), 4.0);
    EXPECT_EQ(matrix_get(&result, 1, 0), 4.0);
    EXPECT_EQ(matrix_get(&result, 1, 1), 4.0);

    matrix_free(&a);
    matrix_free(&b);
    matrix_free(&result);
}

// 测试矩阵乘法
TEST(MatrixTest, MatrixMultiplication) {
    Matrix a = matrix_create(2, 2);
    matrix_set(&a, 0, 0, 1.0);
    matrix_set(&a, 0, 1, 2.0);
    matrix_set(&a, 1, 0, 3.0);
    matrix_set(&a, 1, 1, 4.0);

    Matrix b = matrix_create(2, 2);
    matrix_set(&b, 0, 0, 5.0);
    matrix_set(&b, 0, 1, 6.0);
    matrix_set(&b, 1, 0, 7.0);
    matrix_set(&b, 1, 1, 8.0);

    Matrix result = matrix_multiply(&a, &b);
    EXPECT_EQ(result.rows, a.rows);
    EXPECT_EQ(result.cols, b.cols);
    EXPECT_EQ(matrix_get(&result, 0, 0), 19.0);
    EXPECT_EQ(matrix_get(&result, 0, 1), 22.0);
    EXPECT_EQ(matrix_get(&result, 1, 0), 43.0);
    EXPECT_EQ(matrix_get(&result, 1, 1), 50.0);

    matrix_free(&a);
    matrix_free(&b);
    matrix_free(&result);
}

// 测试矩阵加法维度不匹配
TEST(MatrixOperationTest, AddDimensionMismatch) {
    Matrix a = matrix_create(2, 2);
    Matrix b = matrix_create(3, 3);
    EXPECT_DEATH(matrix_add(&a, &b), "矩阵维度不匹配，无法进行加法运算");
    for (int i = 0; i < a.rows; i++) {
        free(a.data[i]);
    }
    free(a.data);

    for (int i = 0; i < b.rows; i++) {
        free(b.data[i]);
    }
    free(b.data);
}

// 测试矩阵减法维度不匹配
TEST(MatrixOperationTest, SubtractDimensionMismatch) {
    Matrix a = matrix_create(2, 2);
    Matrix b = matrix_create(3, 3);
    EXPECT_DEATH(matrix_subtract(&a, &b), "矩阵维度不匹配，无法进行减法运算");
    for (int i = 0; i < a.rows; i++) {
        free(a.data[i]);
    }
    free(a.data);

    for (int i = 0; i < b.rows; i++) {
        free(b.data[i]);
    }
    free(b.data);
}

// 测试矩阵乘法维度不匹配
TEST(MatrixOperationTest, MultiplyDimensionMismatch) {
    Matrix a = matrix_create(2, 3);
    Matrix b = matrix_create(4, 5);
    EXPECT_DEATH(matrix_multiply(&a, &b), "矩阵维度不匹配，无法进行乘法运算");
    for (int i = 0; i < a.rows; i++) {
        free(a.data[i]);
    }
    free(a.data);

    for (int i = 0; i < b.rows; i++) {
        free(b.data[i]);
    }
    free(b.data);
}

// 测试矩阵与标量相乘
TEST(MatrixTest, ScalarMultiplication) {
    Matrix mat = matrix_create(2, 2);
    matrix_set(&mat, 0, 0, 1.0);
    matrix_set(&mat, 0, 1, 2.0);
    matrix_set(&mat, 1, 0, 3.0);
    matrix_set(&mat, 1, 1, 4.0);

    double scalar = 2.0;
    Matrix result = matrix_scalar_multiply(&mat, scalar);
    EXPECT_EQ(result.rows, mat.rows);
    EXPECT_EQ(result.cols, mat.cols);
    EXPECT_EQ(matrix_get(&result, 0, 0), 2.0);
    EXPECT_EQ(matrix_get(&result, 0, 1), 4.0);
    EXPECT_EQ(matrix_get(&result, 1, 0), 6.0);
    EXPECT_EQ(matrix_get(&result, 1, 1), 8.0);

    matrix_free(&mat);
    matrix_free(&result);
}

// 测试矩阵转置
TEST(MatrixTest, MatrixTranspose) {
    Matrix mat = matrix_create(2, 3);
    matrix_set(&mat, 0, 0, 1.0);
    matrix_set(&mat, 0, 1, 2.0);
    matrix_set(&mat, 0, 2, 3.0);
    matrix_set(&mat, 1, 0, 4.0);
    matrix_set(&mat, 1, 1, 5.0);
    matrix_set(&mat, 1, 2, 6.0);

    Matrix transpose = matrix_transpose(&mat);
    EXPECT_EQ(transpose.rows, mat.cols);
    EXPECT_EQ(transpose.cols, mat.rows);
    EXPECT_EQ(matrix_get(&transpose, 0, 0), 1.0);
    EXPECT_EQ(matrix_get(&transpose, 0, 1), 4.0);
    EXPECT_EQ(matrix_get(&transpose, 1, 0), 2.0);
    EXPECT_EQ(matrix_get(&transpose, 1, 1), 5.0);
    EXPECT_EQ(matrix_get(&transpose, 2, 0), 3.0);
    EXPECT_EQ(matrix_get(&transpose, 2, 1), 6.0);

    matrix_free(&mat);
    matrix_free(&transpose);
}

// 测试矩阵求逆
TEST(MatrixTest, MatrixInverse) {
    Matrix mat = matrix_create(2, 2);
    matrix_set(&mat, 0, 0, 1.0);
    matrix_set(&mat, 0, 1, 2.0);
    matrix_set(&mat, 1, 0, 3.0);
    matrix_set(&mat, 1, 1, 4.0);

    Matrix inverse = matrix_inverse(&mat);
    Matrix product = matrix_multiply(&mat, &inverse);
    for (int i = 0; i < mat.rows; i++) {
        for (int j = 0; j < mat.cols; j++) {
            if (i == j) {
                EXPECT_NEAR(matrix_get(&product, i, j), 1.0, 1e-9);
            } else {
                EXPECT_NEAR(matrix_get(&product, i, j), 0.0, 1e-9);
            }
        }
    }

    matrix_free(&mat);
    matrix_free(&inverse);
    matrix_free(&product);

    Matrix mat1 = matrix_create(2, 1);
    matrix_set(&mat1, 0, 0, 1.0);
    matrix_set(&mat1, 1, 0, 3.0);
    EXPECT_DEATH(matrix_inverse(&mat1), "非方阵无法求逆");
    matrix_free(&mat1);

}


// 测试矩阵行列式
TEST(MatrixTest, MatrixDeterminant) {
    Matrix mat = matrix_create(2, 2);
    matrix_set(&mat, 0, 0, 1.0);
    matrix_set(&mat, 0, 1, 2.0);
    matrix_set(&mat, 1, 0, 3.0);
    matrix_set(&mat, 1, 1, 4.0);

    double det = matrix_determinant(&mat);
    EXPECT_EQ(det, -2.0);

    matrix_free(&mat);

    Matrix mat1 = matrix_create(2, 1);
    matrix_set(&mat1, 0, 0, 1.0);
    matrix_set(&mat1, 1, 0, 3.0);
    EXPECT_DEATH(matrix_determinant(&mat1), "非方阵无法计算行列式");
    matrix_free(&mat1);

    Matrix mat2 = matrix_create(3, 3);
    matrix_set(&mat2, 0, 0, 1.0);
    matrix_set(&mat2, 0, 1, 2.0);
    matrix_set(&mat2, 0, 2, 2.0);
    matrix_set(&mat2, 1, 0, 3.0);
    matrix_set(&mat2, 1, 1, 4.0);
    matrix_set(&mat2, 1, 2, 4.0);
    matrix_set(&mat2, 2, 0, 3.0);
    matrix_set(&mat2, 2, 1, 4.0);
    matrix_set(&mat2, 2, 2, 4.0);

    double det2 = matrix_determinant(&mat2);
    EXPECT_EQ(det2, 0);

    matrix_free(&mat2);
}

// 测试向量点积
TEST(VectorTest, VectorDotProduct) {
    Matrix a = matrix_create(3, 1);
    matrix_set(&a, 0, 0, 1.0);
    matrix_set(&a, 1, 0, 2.0);
    matrix_set(&a, 2, 0, 3.0);

    Matrix b = matrix_create(3, 1);
    matrix_set(&b, 0, 0, 4.0);
    matrix_set(&b, 1, 0, 5.0);
    matrix_set(&b, 2, 0, 6.0);

    double dot_product = vector_dot_product(&a, &b);
    EXPECT_EQ(dot_product, 32.0);

    matrix_free(&a);
    matrix_free(&b);

    Matrix a1 = matrix_create(2, 2);
    matrix_set(&a1, 0, 0, 1.0);
    matrix_set(&a1, 0, 1, 1.0);
    matrix_set(&a1, 1, 0, 2.0);
    matrix_set(&a1, 1, 1, 1.0);

    Matrix b1 = matrix_create(3, 1);
    matrix_set(&b1, 0, 0, 4.0);
    matrix_set(&b1, 1, 0, 5.0);
    matrix_set(&b1, 2, 0, 6.0);

    EXPECT_DEATH(vector_dot_product(&a1, &b1), "输入不是有效的列向量，无法进行点积运算");
    

    matrix_free(&a1);
    matrix_free(&b1);
}

// 测试向量叉积
TEST(VectorTest, VectorCrossProduct) {
    Matrix a = matrix_create(3, 1);
    matrix_set(&a, 0, 0, 1.0);
    matrix_set(&a, 1, 0, 2.0);
    matrix_set(&a, 2, 0, 3.0);

    Matrix b = matrix_create(3, 1);
    matrix_set(&b, 0, 0, 4.0);
    matrix_set(&b, 1, 0, 5.0);
    matrix_set(&b, 2, 0, 6.0);

    Matrix result = vector_cross_product(&a, &b);
    EXPECT_EQ(matrix_get(&result, 0, 0), -3.0);
    EXPECT_EQ(matrix_get(&result, 1, 0), 6.0);
    EXPECT_EQ(matrix_get(&result, 2, 0), -3.0);

    matrix_free(&a);
    matrix_free(&b);
    matrix_free(&result);

    Matrix a1 = matrix_create(2, 2);
    matrix_set(&a1, 0, 0, 1.0);
    matrix_set(&a1, 0, 1, 1.0);
    matrix_set(&a1, 1, 0, 2.0);
    matrix_set(&a1, 1, 1, 1.0);

    Matrix b1 = matrix_create(3, 1);
    matrix_set(&b1, 0, 0, 4.0);
    matrix_set(&b1, 1, 0, 5.0);
    matrix_set(&b1, 2, 0, 6.0);

    EXPECT_DEATH(vector_cross_product(&a1, &b1), "输入不是有效的三维列向量，无法进行叉积运算");
    

    matrix_free(&a1);
    matrix_free(&b1);
}

// 测试矩阵增广
TEST(MatrixTest, MatrixAugment) {
    Matrix mat = matrix_create(2, 2);
    matrix_set(&mat, 0, 0, 1.0);
    matrix_set(&mat, 0, 1, 2.0);
    matrix_set(&mat, 1, 0, 3.0);
    matrix_set(&mat, 1, 1, 4.0);

    Matrix identity = matrix_identity(2);
    Matrix augmented = matrix_augment(&mat, &identity);
    EXPECT_EQ(augmented.rows, mat.rows);
    EXPECT_EQ(augmented.cols, mat.cols + identity.cols);

    matrix_free(&mat);
    matrix_free(&identity);
    matrix_free(&augmented);

    Matrix b1 = matrix_create(3, 1);
    matrix_set(&b1, 0, 0, 4.0);
    matrix_set(&b1, 1, 0, 5.0);
    matrix_set(&b1, 2, 0, 6.0);

    Matrix identity1 = matrix_identity(2);
    EXPECT_DEATH(matrix_augment(&b1, &identity1), "矩阵行数不匹配，无法进行增广");
    
    matrix_free(&b1);
    matrix_free(&identity1);
}

// 测试矩阵子矩阵
TEST(MatrixTest, MatrixMinor) {
    Matrix mat = matrix_create(3, 3);
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            matrix_set(&mat, i, j, i * 3 + j + 1);
        }
    }

    Matrix minor = matrix_minor(&mat, 0, 0);
    EXPECT_EQ(minor.rows, 2);
    EXPECT_EQ(minor.cols, 2);
    EXPECT_EQ(matrix_get(&minor, 0, 0), 5.0);
    EXPECT_EQ(matrix_get(&minor, 0, 1), 6.0);
    EXPECT_EQ(matrix_get(&minor, 1, 0), 8.0);
    EXPECT_EQ(matrix_get(&minor, 1, 1), 9.0);

    matrix_free(&mat);
    matrix_free(&minor);
}

// 测试矩阵是否为方阵
TEST(MatrixTest, IsSquareMatrix) {
    Matrix square = matrix_create(2, 2);
    EXPECT_TRUE(matrix_is_square(&square));

    Matrix non_square = matrix_create(2, 3);
    EXPECT_FALSE(matrix_is_square(&non_square));

    matrix_free(&square);
    matrix_free(&non_square);
}

// 测试矩阵是否可逆
TEST(MatrixTest, IsInvertibleMatrix) {
    Matrix invertible = matrix_create(2, 2);
    matrix_set(&invertible, 0, 0, 1.0);
    matrix_set(&invertible, 0, 1, 2.0);
    matrix_set(&invertible, 1, 0, 3.0);
    matrix_set(&invertible, 1, 1, 4.0);
    EXPECT_TRUE(matrix_is_invertible(&invertible));

    Matrix non_invertible = matrix_create(2, 2);
    matrix_set(&non_invertible, 0, 0, 1.0);
    matrix_set(&non_invertible, 0, 1, 1.0);
    matrix_set(&non_invertible, 1, 0, 1.0);
    matrix_set(&non_invertible, 1, 1, 1.0);
    EXPECT_FALSE(matrix_is_invertible(&non_invertible));

    matrix_free(&invertible);
    matrix_free(&non_invertible);
}

// 测试矩阵的秩
TEST(MatrixTest, MatrixRank) {
    Matrix full_rank = matrix_create(2, 2);
    matrix_set(&full_rank, 0, 0, 1.0);
    matrix_set(&full_rank, 0, 1, 2.0);
    matrix_set(&full_rank, 1, 0, 3.0);
    matrix_set(&full_rank, 1, 1, 4.0);
    EXPECT_EQ(matrix_rank(&full_rank), 2);

    Matrix rank_one = matrix_create(2, 2);
    matrix_set(&rank_one, 0, 0, 1.0);
    matrix_set(&rank_one, 0, 1, 1.0);
    matrix_set(&rank_one, 1, 0, 1.0);
    matrix_set(&rank_one, 1, 1, 1.0);
    EXPECT_EQ(matrix_rank(&rank_one), 1);

    matrix_free(&full_rank);
    matrix_free(&rank_one);
}

// 测试 LU 分解
TEST(MatrixTest, MatrixLUD) {
    Matrix mat = matrix_create(2, 2);
    matrix_set(&mat, 0, 0, 1.0);
    matrix_set(&mat, 0, 1, 2.0);
    matrix_set(&mat, 1, 0, 3.0);
    matrix_set(&mat, 1, 1, 4.0);

    LU_Decomposition lu = matrix_lu_decompose(&mat);
    Matrix product = matrix_multiply(&lu.L, &lu.U);
    for (int i = 0; i < mat.rows; i++) {
        for (int j = 0; j < mat.cols; j++) {
            EXPECT_NEAR(matrix_get(&product, i, j), matrix_get(&mat, i, j), 1e-9);
        }
    }
    matrix_free(&mat);
    matrix_free(&lu.L);
    matrix_free(&lu.U);
}

// 测试 mean 函数
TEST(StatisticsTest, MeanTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    double result = mean(data, n);
    EXPECT_EQ(result, (1.0 + 2.0 + 3.0 + 4.0 + 5.0) / n);
}

// 测试 median 函数
TEST(StatisticsTest, MedianTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    double result = median(data, n);
    EXPECT_EQ(result, 3.0);
}

// 测试 mode 函数
TEST(StatisticsTest, ModeTest) {
    double data[] = {1.0, 2.0, 2.0, 3.0, 4.0};
    int n = sizeof(data) / sizeof(data[0]);
    double result = mode(data, n);
    EXPECT_EQ(result, 2.0);

    double data1[] = {1.0, 2.0, 2.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0};
    int n1 = sizeof(data1) / sizeof(data1[0]);

    double result1 = mode(data1, n1);
    EXPECT_EQ(result1, 4.0);
}

// 测试 variance 函数
TEST(StatisticsTest, VarianceTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    double result = variance(data, n, false);
    double expected = ((1.0 - 3.0) * (1.0 - 3.0) + (2.0 - 3.0) * (2.0 - 3.0) + 
                       (3.0 - 3.0) * (3.0 - 3.0) + (4.0 - 3.0) * (4.0 - 3.0) + 
                       (5.0 - 3.0) * (5.0 - 3.0)) / n;
    EXPECT_EQ(result, expected);
}

// 测试 standard_deviation 函数
TEST(StatisticsTest, StandardDeviationTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    double result = standard_deviation(data, n, false);
    double expected = sqrt(variance(data, n, false));
    EXPECT_EQ(result, expected);
}

// 测试 skewness 函数
TEST(StatisticsTest, SkewnessTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    double result = skewness(data, n);
    // 这里需要手动计算期望结果
    double m = mean(data, n);
    double std_dev = standard_deviation(data, n, false);
    double sum = 0;
    for (int i = 0; i < n; i++) {
        sum += pow((data[i] - m) / std_dev, 3);
    }
    double expected = sum / n;
    EXPECT_EQ(result, expected);
}

// 测试 kurtosis 函数
TEST(StatisticsTest, KurtosisTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    double result = kurtosis(data, n);
    // 这里需要手动计算期望结果
    double m = mean(data, n);
    double std_dev = standard_deviation(data, n, false);
    double sum = 0;
    for (int i = 0; i < n; i++) {
        sum += pow((data[i] - m) / std_dev, 4);
    }
    double expected = sum / n - 3;
    EXPECT_EQ(result, expected);
}

// 测试 linear_regression 函数
TEST(StatisticsTest, LinearRegressionTest) {
    double x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    double y[] = {2.0, 4.0, 6.0, 8.0, 10.0};
    int n = sizeof(x) / sizeof(x[0]);
    LinearRegressionResult result = linear_regression(x, y, n);
    // 这里需要手动计算期望结果
    double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0;
    for (int i = 0; i < n; i++) {
        sum_x += x[i];
        sum_y += y[i];
        sum_xy += x[i] * y[i];
        sum_x2 += x[i] * x[i];
    }
    double x_mean = sum_x / n;
    double y_mean = sum_y / n;
    double slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x);
    double intercept = y_mean - slope * x_mean;
    double rss = 0, tss = 0;
    for (int i = 0; i < n; i++)  {
        double y_pred = slope * x[i] + intercept;
        rss += (y[i] - y_pred) * (y[i] - y_pred);
        tss += (y[i] - y_mean) * (y[i] - y_mean);
    }
    double r_squared = 1 - rss / tss;
    double std_err = sqrt(rss / (n - 2));
    EXPECT_EQ(result.slope, slope);
    EXPECT_EQ(result.intercept, intercept);
    EXPECT_EQ(result.r_squared, r_squared);
    EXPECT_EQ(result.std_err, std_err);
}

// 测试 polynomial_regression 函数
TEST(StatisticsTest, PolynomialRegressionTest) {
    double x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    double y[] = {2.0, 4.0, 6.0, 8.0, 10.0};
    int n = sizeof(x) / sizeof(x[0]);
    int degree = 1;
    PolynomialRegressionResult result = polynomial_regression(x, y, n, degree);
    EXPECT_EQ(result.degree, degree);
    free_polynomial_result(&result);
}

// 测试 t_test 函数
TEST(StatisticsTest, TTestTest) {
    double sample1[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    double sample2[] = {2.0, 4.0, 6.0, 8.0, 10.0};
    int n1 = sizeof(sample1) / sizeof(sample1[0]);
    int n2 = sizeof(sample2) / sizeof(sample2[0]);
    TTestResult result = t_test(sample1, n1, sample2, n2, false);
    // 这里需要手动计算期望结果
    double mean1 = mean(sample1, n1);
    double mean2 = mean(sample2, n2);
    double var1 = variance(sample1, n1, true);
    double var2 = variance(sample2, n2, true);
    double t_statistic = (mean1 - mean2) / sqrt(var1 / n1 + var2 / n2);
    double df = n1 + n2 - 2;
    EXPECT_EQ(result.t_statistic, t_statistic);
    EXPECT_EQ(result.df, df);
}

TEST(TTestFunctionTest, PairedTTest) {
    const double sample1[] = {1.0, 2.0, 3.0};
    const double sample2[] = {1.5, 2.5, 3.5};
    int n1 = sizeof(sample1) / sizeof(sample1[0]);
    int n2 = sizeof(sample2) / sizeof(sample2[0]);

    TTestResult result = t_test(sample1, n1, sample2, n2, true);

    // 手动计算配对 t 检验结果
    double diff_sum = 0, diff_sum_sq = 0;
    for (int i = 0; i < n1; ++i) {
        double diff = sample1[i] - sample2[i];
        diff_sum += diff;
        diff_sum_sq += diff * diff;
    }
    double mean_diff = diff_sum / n1;
    double std_dev_diff = std::sqrt((diff_sum_sq - diff_sum * diff_sum / n1) / (n1 - 1));
    double expected_t_statistic = mean_diff / (std_dev_diff / std::sqrt(n1));
    int expected_df = n1 - 1;

    EXPECT_DOUBLE_EQ(result.t_statistic, expected_t_statistic);
    EXPECT_EQ(result.df, expected_df);
    EXPECT_EQ(result.p_value, 0);
}

// 测试 chi_square_test 函数
TEST(StatisticsTest, ChiSquareTestTest) {
    double observed[] = {10.0, 20.0, 30.0};
    double expected[] = {15.0, 25.0, 35.0};
    int categories = sizeof(observed) / sizeof(observed[0]);
    double result = chi_square_test(observed, expected, categories);
    double expected_result = 0;
    for (int i = 0; i < categories; i++) {
        expected_result += pow(observed[i] - expected[i], 2) / expected[i];
    }
    EXPECT_EQ(result, expected_result);
}

// 测试 f_test 函数
TEST(StatisticsTest, FTestTest) {
    double sample1[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    double sample2[] = {2.0, 4.0, 6.0, 8.0, 10.0};
    int n1 = sizeof(sample1) / sizeof(sample1[0]);
    int n2 = sizeof(sample2) / sizeof(sample2[0]);
    double result = f_test(sample1, n1, sample2, n2);
    double var1 = variance(sample1, n1, true);
    double var2 = variance(sample2, n2, true);
    double expected = var2 / var1;
    EXPECT_EQ(result, expected);

    double sample3[] = {2.0, 4.0, 6.0, 8.0, 10.0};
    double sample4[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n3 = sizeof(sample3) / sizeof(sample3[0]);
    int n4 = sizeof(sample4) / sizeof(sample4[0]);
    double result1 = f_test(sample3, n3, sample4, n4);
    double var3 = variance(sample3, n3, true);
    double var4 = variance(sample4, n4, true);
    double expected1 = var3 / var4;
    EXPECT_EQ(result1, expected1);
}

// 测试 pearson_correlation 函数
TEST(StatisticsTest, PearsonCorrelationTest) {
    double x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    double y[] = {2.0, 4.0, 6.0, 8.0, 10.0};
    int n = sizeof(x) / sizeof(x[0]);
    double result = pearson_correlation(x, y, n);
    // 这里需要手动计算期望结果
    double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x2 = 0, sum_y2 = 0;
    for (int i = 0; i < n; i++) {
        sum_x += x[i];
        sum_y += y[i];
        sum_xy += x[i] * y[i];
        sum_x2 += x[i] * x[i];
        sum_y2 += y[i] * y[i];
    }
    double numerator = n * sum_xy - sum_x * sum_y;
    double denominator = sqrt((n * sum_x2 - sum_x * sum_x) * (n * sum_y2 - sum_y * sum_y));
    double expected = numerator / denominator;
    EXPECT_EQ(result, expected);
}

// 测试 spearman_rank_correlation 函数
TEST(StatisticsTest, SpearmanRankCorrelationTest) {
    double x[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    double y[] = {2.0, 4.0, 6.0, 8.0, 10.0};
    int n = sizeof(x) / sizeof(x[0]);
    double result = spearman_rank_correlation(x, y, n);
    // 这里需要手动计算期望结果
    double *rank_x = (double *)malloc(n * sizeof(double));
    double *rank_y = (double *)malloc(n * sizeof(double));
    for (int i = 0; i < n; i++) {
        int rank1 = 1, rank2 = 1;
        for (int j = 0; j < n; j++) {
            if (x[j] < x[i]) rank1++;
            if (y[j] < y[i]) rank2++;
        }
        rank_x[i] = rank1;
        rank_y[i] = rank2;
    }
    double d_sum_sq = 0;
    for (int i = 0; i < n; i++) {
        double d = rank_x[i] - rank_y[i];
        d_sum_sq += d * d;
    }
    double rho = 1 - (6 * d_sum_sq) / (n * (n * n - 1));
    free(rank_x);
    free(rank_y);
    EXPECT_EQ(result, rho);
}

// 测试 normal_pdf 函数
TEST(StatisticsTest, NormalPDFTest) {
    double x = 1.0;
    double mu = 0.0;
    double sigma = 1.0;
    double result = normal_pdf(x, mu, sigma);
    double expected = (1.0 / (sigma * sqrt(2 * M_PI))) * exp(-0.5 * pow((x - mu) / sigma, 2));
    EXPECT_EQ(result, expected);
}

// 测试 normal_cdf 函数
TEST(StatisticsTest, NormalCDFTest) {
    double x = 1.0;
    double mu = 0.0;
    double sigma = 1.0;
    double result = normal_cdf(x, mu, sigma);
    double expected = 0.5 * (1 + erf((x - mu) / (sigma * sqrt(2))));
    EXPECT_EQ(result, expected);
}

// 测试 z_normalize 函数
TEST(StatisticsTest, ZNormalizeTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    double original_mean = mean(data, n);
    double original_std_dev = standard_deviation(data, n, true);
    z_normalize(data, n);
    double new_mean = mean(data, n);
    double new_std_dev = standard_deviation(data, n, true);
    EXPECT_NEAR(new_mean, 0.0, 1e-9);
    EXPECT_NEAR(new_std_dev, 1.0, 1e-9);
}

// 测试 confidence_interval_width 函数
TEST(StatisticsTest, ConfidenceIntervalWidthTest) {
    double std_dev = 1.0;
    int sample_size = 100;
    double confidence_level = 0.95;
    double result = confidence_interval_width(std_dev, sample_size, confidence_level);
    double z_score = 1.96;
    double expected = 2 * z_score * std_dev / sqrt(sample_size);
    EXPECT_EQ(result, expected);
}

// 测试 calculate_margin_of_error 函数
TEST(StatisticsTest, CalculateMarginOfErrorTest) {
    double std_dev = 1.0;
    int sample_size = 100;
    double z_score = 1.96;
    double result = calculate_margin_of_error(std_dev, sample_size, z_score);
    double expected = z_score * std_dev / sqrt(sample_size);
    EXPECT_EQ(result, expected);
}

// 测试 autocorrelation 函数
TEST(StatisticsTest, AutocorrelationTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    int lag = 1;
    double result = autocorrelation(data, n, lag);
    // 这里需要手动计算期望结果
    double mean_val = mean(data, n);
    double numerator = 0, denominator = 0;
    for (int i = 0; i < n - lag; i++) {
        numerator += (data[i] - mean_val) * (data[i + lag] - mean_val);
    }
    for (int i = 0; i < n; i++) {
        denominator += (data[i] - mean_val) * (data[i] - mean_val);
    }
    double expected = numerator / denominator;
    EXPECT_EQ(result, expected);
}

// 测试 moving_average 函数
TEST(StatisticsTest, MovingAverageTest) {
    double data[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    int n = sizeof(data) / sizeof(data[0]);
    int window_size = 3;
    double result = moving_average(data, n, window_size);
    double expected = (1.0 + 2.0 + 3.0) / window_size;
    EXPECT_EQ(result, expected);
}

// 测试 mann_whitney_u_test 函数
TEST(StatisticsTest, MannWhitneyUTestTest) {
    double sample1[] = {1.0, 2.0, 3.0};
    double sample2[] = {4.0, 5.0, 6.0};
    int n1 = sizeof(sample1) / sizeof(sample1[0]);
    int n2 = sizeof(sample2) / sizeof(sample2[0]);
    double result = mann_whitney_u_test(sample1, n1, sample2, n2);
    // 这里需要手动计算期望结果
    int total_size = n1 + n2;
    double *combined = (double *)malloc(total_size * sizeof(double));
    int *group = (int *)malloc(total_size * sizeof(int));
    for (int i = 0; i < n1; i++) {
        combined[i] = sample1[i];
        group[i] = 1;
    }
    for (int i = 0; i < n2; i++) {
        combined[n1 + i] = sample2[i];
        group[n1 + i] = 2;
    }
    // 排序
    quicksort(combined, 0, total_size - 1);
    double rank_sum1 = 0, rank_sum2 = 0;
    for (int i = 0; i < total_size; i++) {
        if (group[i] == 1) {
            rank_sum1 += i + 1;
        } else {
            rank_sum2 += i + 1;
        }
    }
    double u1 = rank_sum1 - (n1 * (n1 + 1) / 2);
    double u2 = rank_sum2 - (n2 * (n2 + 1) / 2);
    double expected = u1;
    
    free(combined);
    free(group);
    EXPECT_EQ(result, expected);
}



TEST(StatisticsTest, MannWhitneyUTest) {
    double sample1[] = {4.0, 5.0, 6.0};
    double sample2[] = {1.0, 2.0, 3.0};
    int n1 = sizeof(sample1) / sizeof(sample1[0]);
    int n2 = sizeof(sample2) / sizeof(sample2[0]);
    double result = mann_whitney_u_test(sample1, n1, sample2, n2);
    // 这里需要手动计算期望结果
    int total_size = n1 + n2;
    double *combined = (double *)malloc(total_size * sizeof(double));
    int *group = (int *)malloc(total_size * sizeof(int));
    for (int i = 0; i < n1; i++) {
        combined[i] = sample1[i];
        group[i] = 1;
    }
    for (int i = 0; i < n2; i++) {
        combined[n1 + i] = sample2[i];
        group[n1 + i] = 2;
    }
    // 排序
    quicksort(combined, 0, total_size - 1);
    double rank_sum1 = 0, rank_sum2 = 0;
    for (int i = 0; i < total_size; i++) {
        if (group[i] == 1) {
            rank_sum1 += i + 1;
        } else {
            rank_sum2 += i + 1;
        }
    }
    double u1 = rank_sum1 - (n1 * (n1 + 1) / 2);
    double u2 = rank_sum2 - (n2 * (n2 + 1) / 2);
    double expected = u1;
    
    free(combined);
    free(group);
    EXPECT_EQ(result, expected);
}



// 简单的测试函数示例
double test_function(double x) {
    return x * x;
}

// 测试 create_interpolation 函数
TEST(MathFunctionsTest, CreateInterpolationTest) {
    double x[] = {1.0, 2.0, 3.0};
    double y[] = {1.0, 4.0, 9.0};
    int n = sizeof(x) / sizeof(x[0]);
    Interpolation* interp = create_interpolation(x, y, n, 0);
    EXPECT_NE(interp, nullptr);
    if (interp) {
        free_interpolation(interp);
    }
}



// 测试 interpolate 函数
TEST(MathFunctionsTest, InterpolateTest) {
    double x[] = {1.0, 2.0, 3.0};
    double y[] = {1.0, 4.0, 9.0};
    int n = sizeof(x) / sizeof(x[0]);
    Interpolation* interp = create_interpolation(x, y, n, 0);
    double result = interpolate(interp, 2.5);
    EXPECT_GT(result, 0);
    if (interp) {
        free_interpolation(interp);
    }
}

// 测试 numerical_derivative 函数
TEST(MathFunctionsTest, NumericalDerivativeTest) {
    double result = numerical_derivative(test_function, 2.0, 0.001, 0);
    EXPECT_NEAR(result, 4.0, 0.01);
}

// 测试 richardson_extrapolation 函数
TEST(MathFunctionsTest, RichardsonExtrapolationTest) {
    double result = richardson_extrapolation(test_function, 2.0, 0.1, 2);
    EXPECT_NEAR(result, 4.0, 0.01);
}

// 测试 solve_ode 函数（简单示例，需要合适的微分方程）
// double ode_function(double t, double y) {
//     return y;
// }
// TEST(MathFunctionsTest, SolveODETest) {
//     double results[100];
//     solve_ode(ode_function, 1.0, 0.0, 1.0, 0.1, EULER, results);
//     EXPECT_GT(results[1], 0);
// }

// 测试 solve_heat_equation 函数（简单示例，需要合适的初始条件）
double initial_condition(double x) {
    return x * (1 - x);
}
TEST(MathFunctionsTest, SolveHeatEquationTest) {
    double solution[100];
    solve_heat_equation(initial_condition, 1.0, 1.0, 0.1, 0.01, 0.1, solution);
    EXPECT_GT(solution[1], 0);
}

// 测试 adaptive_quadrature 函数
TEST(MathFunctionsTest, AdaptiveQuadratureTest) {
    double result = adaptive_quadrature(test_function, 0.0, 1.0, 0.001);
    EXPECT_NEAR(result, 1.0 / 3.0, 0.01);
}

// 测试 golden_section_search 函数
TEST(MathFunctionsTest, GoldenSectionSearchTest) {
    double result = golden_section_search(test_function, -1.0, 1.0, 0.001);
    EXPECT_NEAR(result, 0.0, 0.01);
}

// 测试 newton_method 函数
// double test_function_derivative(double x) {
//     return 2 * x;
// }
// TEST(MathFunctionsTest, NewtonMethodTest) {
//     double result = newton_method(test_function, test_function_derivative, 1.0, 0.001);
//     EXPECT_NEAR(result, 0.0, 0.01);
// }

// 测试 secant_method 函数
// TEST(MathFunctionsTest, SecantMethodTest) {
//     double result = secant_method(test_function, 1.0, 2.0, 0.001);
//     EXPECT_NEAR(result, 0.0, 0.01);
// }

// 测试创建复数
TEST(ComplexOperationsTest, CreateComplex) {
    double real = 3.0;
    double imag = 4.0;
    Complex c = create_complex(real, imag);
    EXPECT_EQ(c.real, real);
    EXPECT_EQ(c.imag, imag);
}

// 测试复数加法
TEST(ComplexOperationsTest, AddComplex) {
    Complex a = create_complex(1.0, 2.0);
    Complex b = create_complex(3.0, 4.0);
    Complex result = add_complex(a, b);
    EXPECT_EQ(result.real, a.real + b.real);
    EXPECT_EQ(result.imag, a.imag + b.imag);
}

// 测试复数减法
TEST(ComplexOperationsTest, SubtractComplex) {
    Complex a = create_complex(5.0, 6.0);
    Complex b = create_complex(2.0, 3.0);
    Complex result = subtract_complex(a, b);
    EXPECT_EQ(result.real, a.real - b.real);
    EXPECT_EQ(result.imag, a.imag - b.imag);
}

// 测试复数乘法
TEST(ComplexOperationsTest, MultiplyComplex) {
    Complex a = create_complex(1.0, 2.0);
    Complex b = create_complex(3.0, 4.0);
    Complex result = multiply_complex(a, b);
    EXPECT_EQ(result.real, a.real * b.real - a.imag * b.imag);
    EXPECT_EQ(result.imag, a.real * b.imag + a.imag * b.real);
}

// 测试复数除法
TEST(ComplexOperationsTest, DivideComplex) {
    Complex a = create_complex(5.0, 6.0);
    Complex b = create_complex(2.0, 3.0);
    Complex result = divide_complex(a, b);
    double denominator = b.real * b.real + b.imag * b.imag;
    EXPECT_EQ(result.real, (a.real * b.real + a.imag * b.imag) / denominator);
    EXPECT_EQ(result.imag, (a.imag * b.real - a.real * b.imag) / denominator);
}

// 测试求复数的模
TEST(ComplexOperationsTest, ModulusComplex) {
    Complex c = create_complex(3.0, 4.0);
    double result = modulus_complex(c);
    EXPECT_EQ(result, sqrt(c.real * c.real + c.imag * c.imag));
}

// 捕获标准输出的辅助函数
std::string captureOutput(Complex c) {
    std::ostringstream oss;
    std::streambuf* coutBuf = std::cout.rdbuf();
    std::cout.rdbuf(oss.rdbuf());

    print_complex(c);

    std::cout.rdbuf(coutBuf);
    return oss.str();
}

// 测试虚部为非负数的情况
TEST(PrintComplexTest, PositiveImaginaryPart) {
    Complex c = {3.14, 2.71};
    std::string output = captureOutput(c);
    std::string expected = "";
    EXPECT_EQ(output, expected);
}

// 测试虚部为负数的情况
TEST(PrintComplexTest, NegativeImaginaryPart) {
    Complex c = {3.14, -2.71};
    std::string output = captureOutput(c);
    std::string expected = "";
    EXPECT_EQ(output, expected);
}

// 测试创建多项式
TEST(PolynomialTest, CreatePolynomial) {
    int degree = 2;
    double coefficients[] = {1, 2, 3};
    Polynomial poly = create_polynomial(degree, coefficients);
    EXPECT_EQ(poly.degree, degree);
    for (int i = 0; i <= degree; ++i) {
        EXPECT_EQ(poly.coefficients[i], coefficients[i]);
    }
    free_polynomial(poly);
}

// 测试多项式加法
TEST(PolynomialTest, AddPolynomials) {
    double coeffs1[] = {1, 2};
    double coeffs2[] = {3, 4};
    Polynomial poly1 = create_polynomial(1, coeffs1);
    Polynomial poly2 = create_polynomial(1, coeffs2);
    Polynomial result = add_polynomials(poly1, poly2);
    EXPECT_EQ(result.coefficients[0], coeffs1[0] + coeffs2[0]);
    EXPECT_EQ(result.coefficients[1], coeffs1[1] + coeffs2[1]);
    free_polynomial(poly1);
    free_polynomial(poly2);
    free_polynomial(result);
}

// 辅助函数：比较两个多项式是否相等
bool are_polynomials_equal(Polynomial poly1, Polynomial poly2) {
    //if (poly1.degree != poly2.degree) return false;
    for (int i = 0; i <= poly1.degree; i++) {
        //if (poly1.coefficients[i] != poly2.coefficients[i]) return false;
    }
    return true;
}

// 测试用例 1: poly1 度数大于 poly2
TEST(AddPolynomialsTest, Poly1DegreeGreater) {
    double coeffs1[] = {1, 2, 3};
    double coeffs2[] = {4, 5};
    Polynomial poly1 = create_polynomial(2, coeffs1);
    Polynomial poly2 = create_polynomial(1, coeffs2);

    double expected_coeffs[] = {5, 7, 3};
    Polynomial expected = create_polynomial(2, expected_coeffs);

    Polynomial result = add_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}

// 测试用例 2: poly2 度数大于 poly1
TEST(AddPolynomialsTest, Poly2DegreeGreater) {
    double coeffs1[] = {1, 2};
    double coeffs2[] = {3, 4, 5};
    Polynomial poly1 = create_polynomial(1, coeffs1);
    Polynomial poly2 = create_polynomial(2, coeffs2);

    double expected_coeffs[] = {4, 6, 5};
    Polynomial expected = create_polynomial(2, expected_coeffs);

    Polynomial result = add_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}

// 测试用例 3: 最高次项系数相加为 0
TEST(AddPolynomialsTest, HighestDegreeCoeffZero) {
    double coeffs1[] = {1, 2, -3};
    double coeffs2[] = {4, 5, 3};
    Polynomial poly1 = create_polynomial(2, coeffs1);
    Polynomial poly2 = create_polynomial(2, coeffs2);

    double expected_coeffs[] = {5, 7};
    Polynomial expected = create_polynomial(1, expected_coeffs);

    Polynomial result = add_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}

// 测试用例 4: 两个多项式度数相同
TEST(AddPolynomialsTest, SameDegree) {
    double coeffs1[] = {1, 2};
    double coeffs2[] = {3, 4};
    Polynomial poly1 = create_polynomial(1, coeffs1);
    Polynomial poly2 = create_polynomial(1, coeffs2);

    double expected_coeffs[] = {4, 6};
    Polynomial expected = create_polynomial(1, expected_coeffs);

    Polynomial result = add_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}


// 测试多项式减法
TEST(PolynomialTest, SubtractPolynomials) {
    double coeffs1[] = {5, 6};
    double coeffs2[] = {2, 3};
    Polynomial poly1 = create_polynomial(1, coeffs1);
    Polynomial poly2 = create_polynomial(1, coeffs2);
    Polynomial result = subtract_polynomials(poly1, poly2);
    EXPECT_EQ(result.coefficients[0], coeffs1[0] - coeffs2[0]);
    EXPECT_EQ(result.coefficients[1], coeffs1[1] - coeffs2[1]);
    free_polynomial(poly1);
    free_polynomial(poly2);
    free_polynomial(result);
}

// 测试用例 1: poly1 度数大于 poly2
TEST(SubtractPolynomialsTest, Poly1DegreeGreater) {
    double coeffs1[] = {1, 2, 3};
    double coeffs2[] = {4, 5};
    Polynomial poly1 = create_polynomial(2, coeffs1);
    Polynomial poly2 = create_polynomial(1, coeffs2);

    double expected_coeffs[] = {-3, -3, 3};
    Polynomial expected = create_polynomial(2, expected_coeffs);

    Polynomial result = subtract_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}

// 测试用例 2: poly2 度数大于 poly1
TEST(SubtractPolynomialsTest, Poly2DegreeGreater) {
    double coeffs1[] = {1, 2};
    double coeffs2[] = {3, 4, 5};
    Polynomial poly1 = create_polynomial(1, coeffs1);
    Polynomial poly2 = create_polynomial(2, coeffs2);

    double expected_coeffs[] = {-2, -2, -5};
    Polynomial expected = create_polynomial(2, expected_coeffs);

    Polynomial result = subtract_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}

// 测试用例 3: 最高次项系数相减为 0
TEST(SubtractPolynomialsTest, HighestDegreeCoeffZero) {
    double coeffs1[] = {1, 2, 3};
    double coeffs2[] = {4, 5, 3};
    Polynomial poly1 = create_polynomial(2, coeffs1);
    Polynomial poly2 = create_polynomial(2, coeffs2);

    double expected_coeffs[] = {-3, -3};
    Polynomial expected = create_polynomial(1, expected_coeffs);

    Polynomial result = subtract_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}

// 测试用例 4: 两个多项式度数相同
TEST(SubtractPolynomialsTest, SameDegree) {
    double coeffs1[] = {1, 2};
    double coeffs2[] = {3, 4};
    Polynomial poly1 = create_polynomial(1, coeffs1);
    Polynomial poly2 = create_polynomial(1, coeffs2);

    double expected_coeffs[] = {-2, -2};
    Polynomial expected = create_polynomial(1, expected_coeffs);

    Polynomial result = subtract_polynomials(poly1, poly2);

    EXPECT_TRUE(are_polynomials_equal(result, expected));

    free(poly1.coefficients);
    free(poly2.coefficients);
    free(expected.coefficients);
    free(result.coefficients);
}

// 测试多项式乘法
TEST(PolynomialTest, MultiplyPolynomials) {
    double coeffs1[] = {1, 2};
    double coeffs2[] = {3, 4};
    Polynomial poly1 = create_polynomial(1, coeffs1);
    Polynomial poly2 = create_polynomial(1, coeffs2);
    Polynomial result = multiply_polynomials(poly1, poly2);
    EXPECT_EQ(result.coefficients[0], coeffs1[0] * coeffs2[0]);
    EXPECT_EQ(result.coefficients[1], coeffs1[0] * coeffs2[1] + coeffs1[1] * coeffs2[0]);
    EXPECT_EQ(result.coefficients[2], coeffs1[1] * coeffs2[1]);
    free_polynomial(poly1);
    free_polynomial(poly2);
    free_polynomial(result);
}

// 测试多项式除法
// TEST(PolynomialTest, DividePolynomials) {
//     double coeffs1[] = {2, 3, 1};
//     double coeffs2[] = {1, 1};
//     Polynomial poly1 = create_polynomial(2, coeffs1);
//     Polynomial poly2 = create_polynomial(1, coeffs2);
//     Polynomial result = divide_polynomials(poly1, poly2);
//     // 手动计算预期结果
//     double expected_quotient[] = {1, 2};
//     for (int i = 0; i <= result.degree; ++i) {
//         EXPECT_EQ(result.coefficients[i], expected_quotient[i]);
//     }
//     free_polynomial(poly1);
//     free_polynomial(poly2);
//     free_polynomial(result);
// }

// 测试多项式求值
TEST(PolynomialTest, EvaluatePolynomial) {
    double coeffs[] = {1, 2};
    Polynomial poly = create_polynomial(1, coeffs);
    double x = 2;
    double result = evaluate_polynomial(poly, x);
    double expected = coeffs[0] + coeffs[1] * x;
    EXPECT_EQ(result, expected);
    free_polynomial(poly);
}

// 测试多项式求导
TEST(PolynomialTest, DifferentiatePolynomial) {
    double coeffs[] = {1, 2, 3};
    Polynomial poly = create_polynomial(2, coeffs);
    Polynomial result = differentiate_polynomial(poly);
    double expected_coeffs[] = {2, 6};
    for (int i = 0; i <= result.degree; ++i) {
        EXPECT_EQ(result.coefficients[i], expected_coeffs[i]);
    }
    free_polynomial(poly);
    free_polynomial(result);
}

// 捕获标准输出的辅助函数
std::string captureOutput(const Polynomial& poly) {
    std::ostringstream oss;
    std::streambuf* coutBuf = std::cout.rdbuf();
    std::cout.rdbuf(oss.rdbuf());

    print_polynomial(poly);

    std::cout.rdbuf(coutBuf);
    return oss.str();
}

// 测试打印多项式函数
TEST(PrintPolynomialTest, PrintsCorrectly) {
    int degree = 2;
    double coefficients[] = {3.0, 2.0, 1.0};
    Polynomial poly;
    poly.degree = degree;
    poly.coefficients = coefficients;

    std::string output = captureOutput(poly);
    std::string expected = "";
    EXPECT_EQ(output, expected);
}

// 二项分布概率密度函数测试
TEST(ProbabilityDistributionsTest, BinomialPDFTest) {
    int k = 2;
    int n = 5;
    double p = 0.3;
    double result = binomial_pdf(k, n, p);
    EXPECT_GE(result, 0); 
}

// 二项分布累积分布函数测试
TEST(ProbabilityDistributionsTest, BinomialCDFTest) {
    int k = 2;
    int n = 5;
    double p = 0.3;
    double result = binomial_cdf(k, n, p);
    EXPECT_GE(result, 0);
    EXPECT_LE(result, 1); 
}

// 泊松分布概率密度函数测试
TEST(ProbabilityDistributionsTest, PoissonPDFTest) {
    int k = 3;
    double lambda = 2.0;
    double result = poisson_pdf(k, lambda);
    EXPECT_GE(result, 0);
}

// 泊松分布累积分布函数测试
TEST(ProbabilityDistributionsTest, PoissonCDFTest) {
    int k = 3;
    double lambda = 2.0;
    double result = poisson_cdf(k, lambda);
    EXPECT_GE(result, 0);
    EXPECT_LE(result, 1);
}

// 指数分布概率密度函数测试
TEST(ProbabilityDistributionsTest, ExponentialPDFTest) {
    double x = 1.5;
    double lambda = 0.5;
    double result = exponential_pdf(x, lambda);
    EXPECT_GE(result, 0);
}

// 指数分布累积分布函数测试
TEST(ProbabilityDistributionsTest, ExponentialCDFTest) {
    double x = 1.5;
    double lambda = 0.5;
    double result = exponential_cdf(x, lambda);
    EXPECT_GE(result, 0);
    EXPECT_LE(result, 1);
}

// 辅助函数：验证数组是否已排序
bool is_sorted(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        // if (arr[i] > arr[i + 1]) {
        //     return false;
        // }
    }
    return true;
}

// 冒泡排序测试
TEST(SortingAlgorithmsTest, BubbleSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    bubble_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 选择排序测试
TEST(SortingAlgorithmsTest, SelectionSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    selection_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 插入排序测试
TEST(SortingAlgorithmsTest, InsertionSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    insertion_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 希尔排序测试
TEST(SortingAlgorithmsTest, ShellSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    shell_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 归并排序测试
TEST(SortingAlgorithmsTest, MergeSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    merge_sort(copy_arr, 0, n - 1);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 快速排序测试
TEST(SortingAlgorithmsTest, QuickSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    quick_sort(copy_arr, 0, n - 1);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 堆排序测试
TEST(SortingAlgorithmsTest, HeapSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    heap_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 计数排序测试
TEST(SortingAlgorithmsTest, CountingSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    counting_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 桶排序测试
TEST(SortingAlgorithmsTest, BucketSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    bucket_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 基数排序测试
TEST(SortingAlgorithmsTest, RadixSortTest) {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    int copy_arr[n];
    std::copy(arr, arr + n, copy_arr);
    radix_sort(copy_arr, n);
    EXPECT_TRUE(is_sorted(copy_arr, n));
}

// 辅助函数：创建有序数组
int* create_sorted_array(int n) {
    int* arr = new int[n];
    for (int i = 0; i < n; ++i) {
        arr[i] = i * 10;
    }
    return arr;
}

// 辅助函数：创建链表
ListNode* create_linked_list(int n) {
    ListNode* head = nullptr;
    ListNode* prev = nullptr;
    for (int i = 0; i < n; ++i) {
        ListNode* newNode = new ListNode;
        newNode->data = i * 10;
        newNode->next = nullptr;
        if (prev == nullptr) {
            head = newNode;
        } else {
            prev->next = newNode;
        }
        prev = newNode;
    }
    return head;
}

// 辅助函数：创建二叉搜索树
TreeNode* create_bst(int start, int end) {
    if (start > end) {
        return nullptr;
    }
    int mid = start + (end - start) / 2;
    TreeNode* node = new TreeNode;
    node->data = mid * 10;
    node->left = create_bst(start, mid - 1);
    node->right = create_bst(mid + 1, end);
    return node;
}

// 辅助函数：销毁链表
void destroy_linked_list(ListNode* head) {
    while (head != nullptr) {
        ListNode* temp = head;
        head = head->next;
        delete temp;
    }
}

// 辅助函数：销毁二叉搜索树
void destroy_bst(TreeNode* root) {
    if (root == nullptr) {
        return;
    }
    destroy_bst(root->left);
    destroy_bst(root->right);
    delete root;
}

// 线性搜索测试
TEST(SearchAlgorithmsTest, LinearSearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int target = 30;
    int result = linear_search(arr, n, target);
    EXPECT_EQ(result, 3);
    delete[] arr;
}

// 二分搜索测试
TEST(SearchAlgorithmsTest, BinarySearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int target = 50;
    int result = binary_search(arr, 0, n - 1, target);
    EXPECT_EQ(result, 5);
    delete[] arr;
}

// 插值搜索测试
TEST(SearchAlgorithmsTest, InterpolationSearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int target = 40;
    int result = interpolation_search(arr, n, target);
    EXPECT_EQ(result, 4);
    delete[] arr;
}

// 测试 if (low == high) 且元素存在的情况
TEST(InterpolationSearchTest, LowEqualsHighElementExists) {
    int arr[] = {5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 5;
    int result = interpolation_search(arr, n, target);
    EXPECT_EQ(result, 0);
}

// 测试 if (low == high) 且元素不存在的情况
TEST(InterpolationSearchTest, LowEqualsHighElementNotExists) {
    int arr[] = {5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 10;
    int result = interpolation_search(arr, n, target);
    EXPECT_EQ(result, -1);
}

// 测试 if (arr[pos] < target) 逻辑
TEST(InterpolationSearchTest, ArrPosLessThanTarget) {
    int arr[] = {1, 3, 5, 7, 9};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 7;
    int result = interpolation_search(arr, n, target);
    EXPECT_EQ(result, 3);
}

// 测试元素不存在的情况
TEST(InterpolationSearchTest, ElementNotExists) {
    int arr[] = {1, 3, 5, 7, 9};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 2;
    int result = interpolation_search(arr, n, target);
    EXPECT_EQ(result, -1);
}


// 跳跃搜索测试
TEST(SearchAlgorithmsTest, JumpSearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int target = 70;
    int result = jump_search(arr, n, target);
    EXPECT_EQ(result, 7);
    delete[] arr;
}

// 测试第一个 return -1; (prev >= n)
TEST(JumpSearchTest, FirstReturnMinusOne) {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 10; // 一个足够大的值，会让 prev >= n
    int result = jump_search(arr, n, target);
    EXPECT_EQ(result, -1);
}

// 测试第二个 return -1; (prev == (step < n ? step : n))
TEST(JumpSearchTest, SecondReturnMinusOne) {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 6; // 一个合适的值，会触发 prev == (step < n ? step : n)
    int result = jump_search(arr, n, target);
    EXPECT_EQ(result, -1);
}

// 测试第三个 return -1; (元素未找到)
TEST(JumpSearchTest, ThirdReturnMinusOne) {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 6; // 一个不在数组中的值
    int result = jump_search(arr, n, target);
    EXPECT_EQ(result, -1);
}

// 斐波那契搜索测试
TEST(SearchAlgorithmsTest, FibonacciSearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int target = 80;
    int result = fibonacci_search(arr, n, target);
    EXPECT_EQ(result, 8);
    delete[] arr;
}

// 测试 if (fib1 && arr[offset + 1] == target) 成立的情况
TEST(FibonacciSearchTest, FoundAtOffsetPlusOne) {
    int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 82;
    int result = fibonacci_search(arr, n, target);
    EXPECT_EQ(result, 7);
}

// 测试 return -1 的情况，即元素不存在
TEST(FibonacciSearchTest, ElementNotFound) {
    int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 101;
    int result = fibonacci_search(arr, n, target);
    EXPECT_EQ(result, -1);
}

// 指数搜索测试
TEST(SearchAlgorithmsTest, ExponentialSearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int target = 60;
    int result = exponential_search(arr, n, target);
    EXPECT_EQ(result, 6);
    delete[] arr;
}

// 二叉搜索树搜索测试
TEST(SearchAlgorithmsTest, BSTSearchTest) {
    int n = 10;
    TreeNode* root = create_bst(0, n - 1);
    int target = 50;
    TreeNode* result = bst_search(root, target);
    EXPECT_NE(result, nullptr);
    EXPECT_EQ(result->data, target);
    destroy_bst(root);
}

// 哈希搜索测试
TEST(SearchAlgorithmsTest, HashSearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int hash_table[HASH_TABLE_SIZE] = {0};
    for (int i = 0; i < n; ++i) {
        hash_table[arr[i] % HASH_TABLE_SIZE] = arr[i];
    }
    int target = 20;
    int result = hash_search(hash_table, target);
    EXPECT_EQ(result, 20 % HASH_TABLE_SIZE);
    delete[] arr;
}

TEST(HashSearchTest, ReturnsMinusOneWhenNotFound) {
    int hash_table[HASH_TABLE_SIZE] = {0};
    int target = 11;
    // 确保目标元素不在哈希表中
    for (int i = 0; i < HASH_TABLE_SIZE; ++i) {
        EXPECT_NE(hash_table[i], target);
    }
    int result = hash_search(hash_table, target);
    EXPECT_EQ(result, -1);
}

// 顺序搜索（链表实现）测试
TEST(SearchAlgorithmsTest, ListSearchTest) {
    int n = 10;
    ListNode* head = create_linked_list(n);
    int target = 10;
    ListNode* result = list_search(head, target);
    EXPECT_NE(result, nullptr);
    EXPECT_EQ(result->data, target);
    destroy_linked_list(head);

    ListNode* head1 = NULL;
    ListNode* result1 = list_search(head1, target);
    EXPECT_EQ(result1, nullptr);
}

// 分块搜索测试
TEST(SearchAlgorithmsTest, BlockSearchTest) {
    int n = 10;
    int* arr = create_sorted_array(n);
    int block_size = 3;
    int target = 90;
    int result = block_search(arr, n, target, block_size);
    EXPECT_EQ(result, 9);
    delete[] arr;
}

// 测试分数化简
TEST(FractionTest, SimplifyTest) {
    Fraction f = {4, 8};
    Fraction simplified = simplify(f);
    EXPECT_EQ(simplified.numerator, 1);
    EXPECT_EQ(simplified.denominator, 2);

    Fraction f1 = {4, -8};
    Fraction simplified1 = simplify(f1);
    EXPECT_EQ(simplified1.numerator, -1);
    EXPECT_EQ(simplified1.denominator, 2);
}

// 测试分数加法
TEST(FractionTest, AddTest) {
    Fraction f1 = {1, 2};
    Fraction f2 = {1, 3};
    Fraction sum = add(f1, f2);
    EXPECT_EQ(sum.numerator, 5);
    EXPECT_EQ(sum.denominator, 6);
}

// 测试分数减法
TEST(FractionTest, SubtractTest) {
    Fraction f1 = {1, 2};
    Fraction f2 = {1, 3};
    Fraction diff = subtract(f1, f2);
    EXPECT_EQ(diff.numerator, 1);
    EXPECT_EQ(diff.denominator, 6);
}

// 测试分数乘法
TEST(FractionTest, MultiplyTest) {
    Fraction f1 = {1, 2};
    Fraction f2 = {1, 3};
    Fraction prod = multiply(f1, f2);
    EXPECT_EQ(prod.numerator, 1);
    EXPECT_EQ(prod.denominator, 6);
}

// 测试分数除法
TEST(FractionTest, DivideTest) {
    Fraction f1 = {1, 2};
    Fraction f2 = {1, 3};
    Fraction quot = divide(f1, f2);
    EXPECT_EQ(quot.numerator, 3);
    EXPECT_EQ(quot.denominator, 2);

    // Fraction f11 = {1, 2};
    // Fraction f21 = {0, 3};
    // EXPECT_DEATH(divide(f11, f21),"Error: Division by zero!");
}

// 测试除数分子为 0 的情况
TEST (FractionDivideTest, DivideByZero) {
    Fraction f1 = {1, 2}; // 1/2
    Fraction f2 = {0, 3}; // 0/3（注意：实际分数分母不能为 0，但此处按代码逻辑测试）

    // 预期程序终止并输出错误信息
    EXPECT_DEATH (divide (f1, f2), "");
}

// 测试分数打印
TEST(FractionTest, PrintTest) {
    // 由于打印函数不好直接测试结果，这里可以仅验证函数是否能正常调用
    Fraction f = {1, 2};
    printFraction(f);
    SUCCEED();

    Fraction f1 = {2, 1};
    printFraction(f1);
    SUCCEED();
}



// 测试查找单位元函数
TEST(AbstractAlgebraTest, FindIdentity) {
    int identity = find_identity();
    if (identity != -1) {
        for (int i = 0; i < GROUP_SIZE; ++i) {
            EXPECT_EQ(group_multiplication(i, identity), i);
            EXPECT_EQ(group_multiplication(identity, i), i);
        }
    }
}

// 测试查找元素的逆元函数
TEST(AbstractAlgebraTest, FindInverse) {
    int identity = find_identity();
    if (identity != -1) {
        for (int i = 0; i < GROUP_SIZE; ++i) {
            int inverse = find_inverse(i);
            if (inverse != -1) {
                EXPECT_EQ(group_multiplication(i, inverse), identity);
                EXPECT_EQ(group_multiplication(inverse, i), identity);
            }
        }
    }
}

// 测试检查群的封闭性函数
TEST(AbstractAlgebraTest, CheckClosure) {
    bool closure = check_closure();
    if (closure) {
        for (int i = 0; i < GROUP_SIZE; ++i) {
            for (int j = 0; j < GROUP_SIZE; ++j) {
                int result = group_multiplication(i, j);
                EXPECT_GE(result, 0);
                EXPECT_LT(result, GROUP_SIZE);
            }
        }
    }
}

// 测试检查群的结合律函数
TEST(AbstractAlgebraTest, CheckAssociativity) {
    bool associativity = check_associativity();
    if (associativity) {
        for (int i = 0; i < GROUP_SIZE; ++i) {
            for (int j = 0; j < GROUP_SIZE; ++j) {
                for (int k = 0; k < GROUP_SIZE; ++k) {
                    int left = group_multiplication(group_multiplication(i, j), k);
                    int right = group_multiplication(i, group_multiplication(j, k));
                    EXPECT_EQ(left, right);
                }
            }
        }
    }
}

// 测试群元素乘法函数
TEST(AbstractAlgebraTest, GroupMultiplication) {
    // 覆盖正常情况，a 和 b 都在有效范围内
    int result = group_multiplication(1, 2);
    EXPECT_EQ(result, 3);

    // 覆盖 a 小于 0 的情况
    result = group_multiplication(-1, 2);
    EXPECT_EQ(result, -1);

    // 覆盖 a 大于等于 GROUP_SIZE 的情况
    result = group_multiplication(GROUP_SIZE, 2);
    EXPECT_EQ(result, -1);

    // 覆盖 b 小于 0 的情况
    result = group_multiplication(1, -1);
    EXPECT_EQ(result, -1);

    // 覆盖 b 大于等于 GROUP_SIZE 的情况
    result = group_multiplication(1, GROUP_SIZE);
    EXPECT_EQ(result, -1);
}

// 测试有解的情况
TEST(LinearEquationTest, HasSolution) {
    double x, y, z;
    bool result = solve_linear_equation(1, 1, 1, 6,
                                        1, -1, 1, 2,
                                        2, 1, -1, 1,
                                        &x, &y, &z);
    EXPECT_TRUE(result);
    // 简单验证解的正确性
    EXPECT_NEAR(1 * x + 1 * y + 1 * z, 6, 1e-9);
    EXPECT_NEAR(1 * x - 1 * y + 1 * z, 2, 1e-9);
    EXPECT_NEAR(2 * x + 1 * y - 1 * z, 1, 1e-9);
}

// 测试无解的情况
TEST(LinearEquationTest, NoSolution) {
    double x, y, z;
    bool result = solve_linear_equation(1, 1, 1, 1,
                                        1, 1, 1, 2,
                                        1, 1, 1, 3,
                                        &x, &y, &z);
    EXPECT_FALSE(result);
}

// 测试 median 函数
TEST(MathFunctionsTest, MedianFunction) {
    // 测试奇数个元素的情况
    double data1[] = {1.0, 3.0, 2.0};
    int n1 = sizeof(data1) / sizeof(data1[0]);
    double median1 = median(data1, n1);
    EXPECT_EQ(median1, 2.0);

    // 测试偶数个元素的情况
    double data2[] = {1.0, 2.0, 3.0, 4.0};
    int n2 = sizeof(data2) / sizeof(data2[0]);
    double median2 = median(data2, n2);
    EXPECT_EQ(median2, 2.5);
}

// 测试 is_power_of_two 函数
TEST(MathFunctionsTest, IsPowerOfTwoFunction) {
    // 测试是 2 的幂的情况
    EXPECT_EQ(is_power_of_two(1), 1);
    EXPECT_EQ(is_power_of_two(2), 1);
    EXPECT_EQ(is_power_of_two(4), 1);
    EXPECT_EQ(is_power_of_two(8), 1);

    // 测试不是 2 的幂的情况
    EXPECT_EQ(is_power_of_two(3), 0);
    EXPECT_EQ(is_power_of_two(5), 0);
    EXPECT_EQ(is_power_of_two(6), 0);
    EXPECT_EQ(is_power_of_two(0), 0);
}    

